package com.xfc.web.controller.school;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfc.message.NoticeMessage;
import com.xfc.school.domain.*;
import com.xfc.school.service.*;
import com.xfc.wx.domain.ScWxUser;
import com.xfc.wx.service.IScWxUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.xfc.common.annotation.Log;
import com.xfc.common.core.controller.BaseController;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.enums.BusinessType;
import com.xfc.common.utils.poi.ExcelUtil;
import com.xfc.common.core.page.TableDataInfo;

/**
 * 销课记录Controller
 * 
 * @author xfc
 * @date 2022-01-02
 */
@RestController
@RequestMapping("/school/marketing")
public class ScMarketingCourseController extends BaseController
{
    @Autowired
    private IScMarketingCourseService scMarketingCourseService;

    @Autowired
    private IScBuyCourseService scBuyCourseService;

    @Autowired
    private IScCourseService courseService;

    @Autowired
    private IScStudentService studentService;

    @Autowired
    private NoticeMessage message;

    @Autowired
    private IScWxUserService wxUserServicer;

    @Autowired
    private IScClassEvaluationFormService classEvaluationFormService;

    /**
     * 查询销课记录列表
     */
    @PreAuthorize("@ss.hasPermi('school:marketing:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScMarketingCourse scMarketingCourse)
    {
        startPage();
        List<ScMarketingCourse> list = scMarketingCourseService.list();
        return getDataTable(list);
    }

    /**
     * 导出销课记录列表
     */
    @PreAuthorize("@ss.hasPermi('school:marketing:export')")
    @Log(title = "销课记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ScMarketingCourse scMarketingCourse)
    {
        List<ScMarketingCourse> list = scMarketingCourseService.list();
        ExcelUtil<ScMarketingCourse> util = new ExcelUtil<ScMarketingCourse>(ScMarketingCourse.class);
        return util.exportExcel(list, "marketing");
    }

    /**
     * 获取销课记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('school:marketing:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(scMarketingCourseService.getById(id));
    }

    /**
     * 新增销课记录
     */
    @Transactional
    @Log(title = "新增销课记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScMarketingCourse scMarketingCourse,ScBuyCourse scBuyCourse)
    {

        scMarketingCourse.setCreateTime(new Date());
        Integer surplusTiem=scMarketingCourse.getClassSurplusTime();
        if(Objects.nonNull(surplusTiem)){
            scBuyCourse.setClassSurplusTime(surplusTiem-scMarketingCourse.getXknumber());
        }
        scBuyCourse.setId(scMarketingCourse.getByclassid());
        scBuyCourseService.updateById(scBuyCourse);
        //查询课程是否已消课
        QueryWrapper<ScMarketingCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_id",scMarketingCourse.getStudentId());
        queryWrapper.eq("course_id",scMarketingCourse.getByclassid());
        queryWrapper.eq("course_startime",scBuyCourse.getCourseStartime());
        queryWrapper.eq("counrse_endtime",scBuyCourse.getCounrseEndtime());
        ScMarketingCourse scMarketingCourse1=scMarketingCourseService.getOne(queryWrapper);
        if (Objects.nonNull(scMarketingCourse1)){
            scMarketingCourse.setId(scMarketingCourse1.getId());
        }
        scMarketingCourseService.saveOrUpdate(scMarketingCourse);
        //消课通知
        ScBuyCourse scBuyCourse1=scBuyCourseService.getById(scMarketingCourse.getByclassid());
        if (Objects.nonNull(scBuyCourse1)){
            //查询课程
            ScCourse course=courseService.getById(scBuyCourse1.getClassId());
            if (Objects.nonNull(course)){
                //查询学生信息
                ScStudent student=studentService.getById(scBuyCourse1.getStudentId());
                if (Objects.nonNull(student)){
                    //查询openid
                    ScWxUser wxUser=wxUserServicer.getOne(new QueryWrapper<ScWxUser>().eq("mobile",student.getStudentMobile()));
                   if (Objects.nonNull(wxUser)) {
                       message.courseDisappear(wxUser.getOpenId(), student.getStudentName(), scMarketingCourse.getCourseStartime(), course.getClassName(), "1", String.valueOf(scBuyCourse.getClassSurplusTime()));
                   }
                }
            }
        }
        return toAjax(true);
    }

    /**
     * 修改销课记录
     */
    @PreAuthorize("@ss.hasPermi('school:marketing:edit')")
    @Log(title = "销课记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScMarketingCourse scMarketingCourse)
    {
        return toAjax(scMarketingCourseService.updateById(scMarketingCourse));
    }

    /**
     * 删除销课记录
     */
    @PreAuthorize("@ss.hasPermi('school:marketing:remove')")
    @Log(title = "销课记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
		List<String> list=new ArrayList<>();
    	if (ids!=null&&ids.length>0) {
            for (String id : ids) {
                list.add(id);
            }
		}
        return toAjax(scMarketingCourseService.removeByIds(list));
    }


    /**
     * 查询学生上课记录评价信息
     */
    @GetMapping("/getStudentEvaluate")
    public AjaxResult getStudentEvaluate(@RequestParam String id){
       //查询消课记录
        ScMarketingCourse marketingCourse=scMarketingCourseService.getById(id);
        if (Objects.isNull(marketingCourse)){
            return AjaxResult.error("没有查询到消课信息");
        }
        QueryWrapper<ScClassEvaluationForm> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("student_number",marketingCourse.getStudentId());
        queryWrapper.eq("course_number",marketingCourse.getCourseId());
        queryWrapper.apply(
                "date_format (start_time,'%Y-%m-%d %h-%m') = date_format('" +marketingCourse.getCourseStartime()+ "','%Y-%m-%d %h-%m')");
        ScClassEvaluationForm ScClassEvaluationForm = classEvaluationFormService.getOne(queryWrapper);
        if (Objects.isNull(ScClassEvaluationForm)){
            return AjaxResult.error("没有查询到评价信息");
        }
        return AjaxResult.success(ScClassEvaluationForm);
    }



}
